<!-- 菜单管理 -->
<template>
  <PageContainer title="菜单管理">
    <div class="menu-operate">
      <el-button type="primary" @click="handleAddRootMenu">
        <i class="el-icon-plus"></i> 添加一级菜单
      </el-button>
      <el-button type="success" @click="handleRefresh">
        <i class="el-icon-refresh"></i> 刷新菜单
      </el-button>
    </div>

    <!-- 菜单树 -->
    <div class="menu-tree-container" style="margin-top: 20px;">
      <el-tree :data="menuTree" :props="treeProps" :expand-on-click-node="false" :default-expanded-keys="expandedKeys"
        border style="width: 100%;">
        <template #default="{ node, data }">
          <div class="tree-node">
            <span>{{ data.name }}</span>
            <span class="node-actions">
              <el-button type="text" size="mini" @click="handleAddSubMenu(data)">添加子菜单</el-button>
              <el-button type="text" size="mini" @click="handleEditMenu(data)">编辑</el-button>
              <el-button type="text" size="mini" style="color: red;"
                @click="handleDeleteMenu(data, node)">删除</el-button>
            </span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 添加/编辑菜单弹窗 -->
    <el-dialog :title="isEdit ? '编辑菜单' : (isSubMenu ? '添加子菜单' : '添加一级菜单')" :visible.sync="dialogVisible" width="500px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入菜单路径（如：/user-manage）"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件路径（如：views/user-manage）"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入Element图标类名（如：el-icon-user）"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序号（数字越小越靠前）"></el-input>
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="显示"
            inactive-text="隐藏"></el-switch>
        </el-form-item>
        <el-form-item label="角色权限" prop="roles">
          <el-select v-model="form.roles" multiple placeholder="请选择可访问该菜单的角色">
            <el-option label="超级管理员" value="super_admin"></el-option>
            <el-option label="商家" value="merchant"></el-option>
            <el-option label="医生" value="doctor"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import { getMenuTree, addMenu, editMenu, deleteMenu } from '@/api/menu'

// 菜单树配置
const treeProps = ref({
  label: 'name',
  children: 'children',
  disabled: (data) => data.isSystem // 系统菜单不可编辑
})

// 菜单数据
const menuTree = ref([])
const expandedKeys = ref([])
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const isSubMenu = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  parentId: '',
  name: '',
  path: '',
  component: '',
  icon: '',
  sort: 0,
  status: 1,
  roles: []
})

// 表单校验规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '请输入数字', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择可访问角色', trigger: 'change' }
  ]
})

// 获取菜单树
const fetchMenuTree = async () => {
  try {
    loading.value = true
    const res = await getMenuTree()
    menuTree.value = res.data
    // 默认展开前两级
    expandedKeys.value = menuTree.value.map(item => item.id)
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

// 添加一级菜单
const handleAddRootMenu = () => {
  isEdit.value = false
  isSubMenu.value = false
  // 重置表单
  form.id = ''
  form.parentId = '0' // 一级菜单父ID为0
  form.name = ''
  form.path = ''
  form.component = ''
  form.icon = ''
  form.sort = 0
  form.status = 1
  form.roles = []
  dialogVisible.value = true
}

// 添加子菜单
const handleAddSubMenu = (data) => {
  isEdit.value = false
  isSubMenu.value = true
  // 重置表单
  form.id = ''
  form.parentId = data.id
  form.name = ''
  form.path = ''
  form.component = ''
  form.icon = ''
  form.sort = 0
  form.status = 1
  form.roles = []
  dialogVisible.value = true
}

// 编辑菜单
const handleEditMenu = (data) => {
  if (data.isSystem) {
    ElMessage.warning('系统菜单不可编辑')
    return
  }

  isEdit.value = true
  isSubMenu.value = data.parentId !== '0'
  // 填充表单
  form.id = data.id
  form.parentId = data.parentId
  form.name = data.name
  form.path = data.path
  form.component = data.component
  form.icon = data.icon
  form.sort = data.sort
  form.status = data.status
  form.roles = data.roles || []
  dialogVisible.value = true
}

// 删除菜单
const handleDeleteMenu = async (data, node) => {
  if (data.isSystem) {
    ElMessage.warning('系统菜单不可删除')
    return
  }

  // 有子菜单不可删除
  if (node.childNodes && node.childNodes.length > 0) {
    ElMessage.warning('该菜单存在子菜单，请先删除子菜单')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要删除该菜单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteMenu(data.id)
    ElMessage.success('删除成功')
    fetchMenuTree()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑菜单
      await editMenu(form)
      ElMessage.success('编辑菜单成功')
    } else {
      // 添加菜单
      await addMenu(form)
      ElMessage.success('添加菜单成功')
    }
    dialogVisible.value = false
    fetchMenuTree()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑菜单失败' : '添加菜单失败')
  }
}

// 刷新菜单
const handleRefresh = () => {
  fetchMenuTree()
  ElMessage.success('菜单已刷新')
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchMenuTree()
})
</script>

<style scoped lang="scss">
.menu-operate {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.menu-tree-container {
  background: #fff;
  border-radius: 4px;
  padding: 10px;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .node-actions {
    opacity: 0;
    transition: opacity 0.3s;
  }
}

.el-tree-node:hover .tree-node .node-actions {
  opacity: 1;
}

:deep(.el-tree-node__content) {
  height: 40px !important;
}
</style>